<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="format-detection" content="telephone=no">
    <meta charset="utf-8">
    <link href="css/index.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.12.0.min.js"></script>
    <script type="text/javascript" src="js/vue.js"></script>
</head>

<body>
<div id="all">
    <iframe  src="chatInfo.html?user=10000000" frameborder="0" style="width: 100vw; height: 100vh">

    </iframe>
</div>
<script type="text/javascript">

    var all = new Vue({
        el : '#all',
        data : {
            url:'ws://192.168.20.10:8282',
            ws:'',
            my:'10000003',
            chatInfo:[],
            chatList:[],
            allNeedViewMessage:{
                num: 0
            }
        },
        methods:{
            //websocket连接
            connectWs:function () {
                all.ws = new WebSocket(all.url);
                all.ws.onopen = all.wsOnOpen;
                all.ws.onmessage = all.wsOnMessage;
                all.ws.onclose = function() {
                    console.log("连接关闭，定时重连");
                };
                all.ws.onerror = function() {
                    console.log("出现错误");
                };
            },
            //websocket监听
            wsOnMessage: function (e) {
                var data = JSON.parse(e.data);
                console.log(data);
                switch(data.type){
                    case 'ping':
                        all.ws.send('{"type":"pong"}');
                        break;
                    case 'get' :
                        break;
                    case 'say' :
                        var chat = {};
                        chat.isBig = false;
                        chat.message = data.message;
                        chat.user_send = data.userSend;
                        chat.user_received = data.userReceived;
                        chat.message_type = data.messageType;
                        chat.date = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                        all.chatInfo.push(chat);
                        break;
                    case 'resChatList':
                        //因直接赋值导致跨iframe 不渲染， 故使用pop推出 all.chatList = [];
//                        var len = all.chatList.length;
//                        while(len--) {
//                            all.chatList.pop();
//                        }
                        $.each(data.data, function (index, value) {
                            var tem = [];
                            tem.img = "images/face.jpg";
                            tem.userid = value['user'];
                            tem.name = value['name'];
                            tem.word = value['value']['message'];
                            tem.date = value['value']['date'];
                            tem.len  = value['len'];
                            all.allNeedViewMessage.num += tem.len;
                            all.chatList.push(tem);
                        });
                        break;
                    case 'resChatInfo':
                        $.each(data.data, function (index, value) {
                            value.isBig = false;
                            all.chatInfo.splice(0, 0, value);
                        });
                        console.log(all.chatInfo);
                        break;
                }
            },
            //打开websocket
            wsOnOpen : function () {
                var bind_data = '{"type":"bind","user1":'+ all.my +'}';
                console.log("绑定成功，发送绑定数据:"+bind_data);
                all.ws.send(bind_data);

                // 登录
                var login_data = '{"type":"login","user1":'+ all.my +'}';
                console.log("握手成功，发送登录数据:"+login_data);
                all.ws.send(login_data);
            },
            //获取聊天列表
            wsGetChatList: function () {
                all.ws.send('{"type":"getChatList", "userid":"'+ all.my +'"}');
            },
            //获取单个聊天记录
            wsGetChatInfo:function (id, page) {
                if (!page) {
                    page = 1;
                }
                console.log('{"type":"getChatInfo", "userid":"'+ all.my +'", "userid2":"'+ id + '", "page":"'+ page + '"}');
                all.ws.send('{"type":"getChatInfo", "userid":"'+ all.my +'", "userid2":"'+ id + '", "page":"'+ page + '"}');
            },
            //发送聊天记录
            wsSendChatList:function (other, msg, type) {
                console.log(other, msg, type);
                all.ws.send('{"type":"say", "userSend":"'+ all.my +'", "userReceived":"'+ other + '", "message":"'+ msg + '", "messageType":"'+ type + '"}');
                var chat = {};
                chat.isBig = false;
                chat.message = msg;
                chat.user_send = all.my;
                chat.user_received = other;
                chat.message_type = type;
                chat.date = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                all.chatInfo.push(chat);
                this.wsGetChatList();
            },
        }
    });
    parent.all.connectWs();

    function formatDate (date, fmt) {
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
            }
        }
        return fmt
    }

    function padLeftZero (str) {
        return ('00' + str).substr(str.length)
    }
</script>
</body>
</html>